package main

import (
	"database/sql"
	//"errors"
	"fmt"
	"strconv"
)

type SEX uint8

var (
	MAN   SEX = 0
	WOMAN SEX = 1
)

func (this SEX) sex() string {
	if this == 0 {
		return "man"
	} else {
		return "woman"
	}
}

/*
 * DB Insert Operation
 */
type InsertUserInfo struct {
	UserInfoDB
	UserTable
	uid  string
	name string
	age  uint8
	sex  uint8
}

func (this *InsertUserInfo) Process(db *sql.DB) {
	//fmt.Printf("InserUserInfo dbname:%s tablename:%s", this.DBName(), this.TableName())
	insert := fmt.Sprintf("INSERT INTO `%s` (`uid`, `name`, `age`, `sex`) VALUES ( \"%s\", \"%s\", %d, %d)", this.TableName(), this.uid, this.name, this.age, this.sex)

	if _, err := db.Exec(insert); err != nil {
		panic("insert user info error:" + err.Error())
	}

	fmt.Printf("\nINSERT SQL:%s \n", insert)
}

/*
 * DB Select Operation
 */
type QueryUserInfo struct {
	UserInfoDB
	UserTable
	uid string
	ret chan map[string]string
}

func (this *QueryUserInfo) Process(db *sql.DB) {
	result := make(map[string]string)
	uid := ""
	name := ""
	var age uint8
	var sex uint8
	// operate DB

	selectUser := fmt.Sprintf("select `uid`, `name`, `age`, `sex` from `%s` where `uid`=\"%s\" ", this.TableName(), this.uid)

	if rows, err := db.Query(selectUser); err != nil {
		panic("select user info error:" + err.Error())
	} else {
		defer rows.Close()

		for rows.Next() {
			if err := rows.Scan(&uid, &name, &age, &sex); err != nil {
				panic("scan user info error:" + err.Error())
			}
			break
		}

		if err := rows.Err(); err != nil {
			panic("rows.Err() error:" + err.Error())
		}
	}

	result["uid"] = uid
	result["name"] = name
	result["age"] = strconv.FormatUint(uint64(age), 10)
	result["sex"] = SEX(sex).sex()

	fmt.Printf("\nSELECT SQL:%s \n", selectUser)
	// return result
	this.ret <- result
}

func (this *QueryUserInfo) Result() <-chan map[string]string {
	return this.ret
}
